<template>
	<view style="padding: 10px;">
		<view>
			<u-form :model="formData" ref="uForm" >
				<u-form-item label="密码:"  border-bottom="false" label-width="150" prop="pwd" >
					<u-input v-model="formData.pwd" type="password" placeholder="请输入密码" />
				</u-form-item>
				<u-form-item label="确认密码:"  border-bottom="false" label-width="150" prop="rePwd" >
					<u-input v-model="formData.rePwd" type="password"  placeholder="请输入确认密码" />
				</u-form-item>
			</u-form>
			<u-button @click="changePwd()" type="primary">修改密码</u-button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import CryptoJS from 'crypto-js';
	import {mapState} from 'vuex';
	const key = CryptoJS.enc.Latin1.parse('abcdef0123456789');
	export default {
		computed:mapState(['user', ]),
		data (){
			return{
				errorType: ['toast','border-bottom'],
				formData:{
					id: '',
					pwd:'',
					rePwd: '',
				},
				rules: {
					pwd: [
						{
							required: true, 
							message: '请输入密码',
							trigger: ['change','blur'],
						},
						{
							// 正则不能含有两边的引号
							pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
							message: '需同时含有字母和数字，长度在6-12之间',
							trigger: ['change','blur'],
						}
					],
					rePwd: [
						{
							required: true, 
							message: '请输入确认密码',
							trigger: ['change','blur'],
						},
						{
							validator: (rule, value, callback) => {
								return value === this.formData.pwd;
							},
							message: '两次输入的密码不相等',
							trigger: ['change','blur'],
						}
					],
				}
			}
		},
		methods:{
			changePwd(){
				this.formData.id = this.user.user.id || '';
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.formData.pwd = this.encrypted(this.formData.pwd);
						let {id,pwd} = this.formData;
						if(id===undefined||id===""){
							this.$refs.uToast.show({
								title: '当前用户id为空',
								type: 'error'				
								})
								flag = false;
							return flag;
						}
						this.$http.post("/user/changePwd",this.formData).then(res=>{
							let data = res.data.data;
							if(data){
								this.$refs.uToast.show({
									title: '密码修改成功,请重新登录',
									type: 'success',
									back: true
								})
							}else{
								this.$refs.uToast.show({
									title: '密码修改失败，请联系管理员',
									type: 'error'
								})
							}
						})
						console.log(this.formData);
						console.log('验证通过');
					} else {
						this.$refs.uToast.show({
							title: '密码验证不通过',
							type: 'error'
						})
						console.log(this.formData);
						console.log('验证失败');
					}
				});
			},
			// 密码加密
			encrypted (pwd) {
				return CryptoJS.AES.encrypt(pwd, key, {
				  mode: CryptoJS.mode.ECB,
				  padding: CryptoJS.pad.Pkcs7
				}).toString();
			}
		},onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
	}
</script>

<style>
</style>
